package com.wdcloud.netlibrary.deliver;

import android.os.Handler;

import com.wdcloud.netlibrary.callback.BaseCallback;
import com.wdcloud.netlibrary.callback.DownloadProgressCallback;
import com.wdcloud.netlibrary.callback.NetWorkCallback;

import java.util.concurrent.Executor;


public class MainThreadDeliver implements IDeliver {

    private final Handler handler;

    private Executor executor;

    public MainThreadDeliver(Handler handler) {

        this.handler = handler;

        executor = new Executor() {
            @Override
            public void execute(Runnable command) {
                MainThreadDeliver.this.handler.post(command);
            }
        };
    }


    public void deliverStart(final BaseCallback callback) {

        executor.execute(new Runnable() {
            @Override
            public void run() {
                callback.onStart();
            }
        });
    }

    public <T> void deliverSuccess(final NetWorkCallback<T> callback, final T t) {

        executor.execute(new Runnable() {
            @Override
            public void run() {
                callback.onSuccess(t);
            }
        });
    }

    public void deliverComplete(final BaseCallback callback) {

        executor.execute(new Runnable() {
            @Override
            public void run() {
                callback.onComplete();
            }
        });
    }

    public void deliverCancel(final BaseCallback callback) {

        executor.execute(new Runnable() {
            @Override
            public void run() {
                callback.onCancel();
            }
        });
    }

    public void deliverFail(final BaseCallback callback, final Exception e) {

        executor.execute(new Runnable() {
            @Override
            public void run() {
                callback.onFail(e);
            }
        });
    }

    public void deliverProgress(final DownloadProgressCallback callback,
                                final long current, final long total, final int progress) {

        executor.execute(new Runnable() {
            @Override
            public void run() {
                callback.onProgress(current, total, progress);
            }
        });
    }
}
